<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves class="el-button filter-item el-button--primary el-button--medium" type="primary" @click="handleFilter('')">
        总数({{ carTotal.total }})
      </el-button>
      <el-button v-waves value="1" class="el-button filter-item el-button--primary el-button--medium" type="primary" @click="handleFilter(1)">
        在线({{ carTotal.ownerOnline }})
      </el-button>
      <el-button v-waves class="el-button filter-item el-button--primary el-button--medium" type="primary" @click="handleFilter(0)">
        离线({{ carTotal.ownerDisOnline }})
      </el-button>
      <el-button v-waves class="el-button filter-item el-button--primary el-button--medium" type="danger" @click="handleFilter(-1)">
        停用({{ carTotal.stopTotal }})
      </el-button>
    </div>
    <div class="filter-container" style="padding: 16px 0;">
      <!-- <el-input v-model="listQuery.driverName" placeholder="司机" style="width: 200px;" class="filter-item el-input--medium" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.ownerName" placeholder="货主" style="width: 200px;" class="filter-item el-input--medium" @keyup.enter.native="handleFilter" /> -->

      <el-input v-model="search.number" placeholder="身份证号码/手机号码" style="width: 200px;" class="filter-item el-input--medium" @keyup.enter.native="searchList" />
      <!-- <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="el-button filter-item el-button--primary el-button--medium" type="primary" icon="el-icon-search" @click="searchList">
        搜索
      </el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="编号" prop="id" sortable="custom" width="170" align="center" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ownerName }}</span>
          <!-- <el-tag>{{ row.ownerName  }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" width="120">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ownerAddress }}</span>
          <!-- <el-tag>{{ row.ownerName  }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="身份证号码" align="center" width="185">
        <template slot-scope="{row}">
          <span>{{ row.idCardNumber }}</span>
          <!-- <el-tag>{{ row.ownerName  }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="身份证" align="center" width="130">
        <template slot-scope="{row}">
          <el-popover v-if="row.idCardImg" placement="top-start" trigger="click"> <!--trigger属性值：hover、click、focus 和 manual-->
            <a :href="row.idCardImg" target="_blank" title="查看最大化图片">
              <img :src="row.idCardImg" style="width: 100%;height: 100%">
            </a>
            <img slot="reference" :src="row.idCardImg" class="carImg" style="cursor:pointer">
          </el-popover>
          <p v-else>未上传</p>
        </template>
      </el-table-column>
      <el-table-column label="公司认证" align="center" width="130">
        <template slot-scope="{row}">
          <div v-if="row.companyImg">
            <el-popover placement="top-start" trigger="click"> <!--trigger属性值：hover、click、focus 和 manual-->
              <a :href="row.companyImg" target="_blank" title="查看最大化图片">
                <img :src="row.companyImg" style="width: 100%;height: 100%">
              </a>
              <img slot="reference" :src="row.companyImg" class="carImg" style="cursor:pointer">
            </el-popover>
            <div v-if="row.companyAuthState!=1" style="text-align:center;font-size: 12px;">(未审核/未审核通过)</div>
          </div>
          <p v-else>未上传</p>
        </template>
      </el-table-column>
      <el-table-column label="订单数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderTotalNumber }}</span>
        </template>
      </el-table-column>
      <!--
      <el-table-column label="好评率" align="center">
        <template slot-scope="{row}">
          <span>{{ row.goodCommentRate }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="推广数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.vehicleVolume }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Imp" width="80px">
        <template slot-scope="{row}">
          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>
      <el-table-column label="Readings" align="center" width="95">
        <template slot-scope="{row}">
          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" @click="openDetail(row.id)">
            编辑
          </el-button>
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
         <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            Publish
          </el-button> -->
          <el-button v-if="row.state!='-2'" size="mini" type="danger" @click="stopCar(row.id)">
            停用
          </el-button>
          <el-button v-if="row.state=='-2'" size="mini" type="success" @click="backCar(row.id)">
            恢复
          </el-button>

          <!-- <el-button v-if="row.state=='-2'" size="mini" type="danger" @click="deleteCar(row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limt.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog ref="drag-dialog" :visible.sync="dialogTableVisible" title="货主详情" label-width="70px" width="80%" top="10px">
      <div>
        <table class="driverDetialTable">
          <tr>
            <td rowspan="5">
              <div
                style="width:100px;height:100px;border-radius: 100px;background-color: #409eff;overflow: hidden;"
              >
                <el-upload
                  class="avatar-uploader"
                  :action="UploadUrl()"
                  :headers="header"
                  :show-file-list="true"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="ownerData.headImg" :src="ownerData.headImg" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
                <!-- <img :src="ownerData.headImg" alt style="width:100px;"> -->
              </div>
              <input v-model="editOwner.nickname">
            </td>
            <td class="tableTitle">用户ID</td>
            <td>{{ ownerData.id }}</td>
          </tr>
          <tr>
            <td class="tableTitle">身份</td>
            <td>{{ ownerData.userType | usertype(ownerData.userType) }}</td>
          </tr>
          <tr>
            <td class="tableTitle">联系电话</td>
            <td>
              <input v-model="editOwner.phone"></td>
          </tr>
          <tr>
            <td class="tableTitle">城市</td>
            <td>
              {{ ownerData.address }}
              <!-- <input v-model="editOwner.address"> -->
            </td>
          </tr>
          <tr>
            <td class="tableTitle">注册时间</td>
            <td>{{ ownerData.userCreateTime| parseTime('{y}-{m}-{d} {h}:{i}') }}</td>
          </tr>
        </table>
      </div>
      <div>
        <div>
          <aside>统计信息</aside>
        </div>
        <el-table :data="ownerTotalData">
          <el-table-column property="outcome" label="支出金额" width="150" />
          <el-table-column property="orderTotal" label="订单数" width="200" />
          <el-table-column property="commentTotal" label="评价数" />
          <el-table-column property="" label="邀请人数" />
        </el-table>
      </div>
      <div>
        <div>
          <aside>身份认证信息</aside>
        </div>
        <el-collapse accordion>
          <el-collapse-item>
            <template slot="title">
              身份证 (<p v-if="ownerData.idState==1">已认证</p><p v-else>未认证</p>)
            </template>
            <div style="display: flex;">
              <el-popover v-if="ownerData.frontImg" placement="top-start" trigger="click">
                <a :href="ownerData.frontImg" target="_blank" title="查看最大化图片">
                  <img :src="ownerData.frontImg" style="width: 100%;height: 100%">
                </a>
                <img slot="reference" :src="ownerData.frontImg" class="carImg" style="cursor:pointer">
              </el-popover>
              <el-upload
                class="upload-demo"
                :action="UploadUrl()"
                :headers="header"
                :show-file-list="false"
                :on-success="handleIdCardImgBSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>
            <div style="display: flex;">
              <el-popover v-if="ownerData.reverseImg" placement="top-start" trigger="click">
                <a :href="ownerData.reverseImg" target="_blank" title="查看最大化图片">
                  <img :src="ownerData.reverseImg" style="width: 100%;height: 100%">
                </a>
                <img slot="reference" :src="ownerData.reverseImg" class="carImg" style="cursor:pointer">
              </el-popover>
              <el-upload
                class="upload-demo"
                :action="UploadUrl()"
                :headers="header"
                :show-file-list="false"
                :on-success="handleIdCardImgFSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>
            <div style="display: flex;">
              <el-popover v-if="ownerData.selfImg" placement="top-start" trigger="click">
                <a :href="ownerData.selfImg" target="_blank" title="查看最大化图片">
                  <img :src="ownerData.selfImg" style="width: 100%;height: 100%">
                </a>
                <img slot="reference" :src="ownerData.selfImg" class="carImg" style="cursor:pointer">
              </el-popover>
              <el-upload
                class="upload-demo"
                :action="UploadUrl()"
                :headers="header"
                :show-file-list="false"
                :on-success="handleSelfImgSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>
          </el-collapse-item>
          <el-collapse-item>
            <template slot="title">
              公司信息 (<p v-if="ownerData.companyState==1">已认证</p><p v-else>未认证</p>)
            </template>
            <div>
              <el-popover v-if="ownerData.licenseImg" placement="top-start" trigger="click">
                <a :href="ownerData.licenseImg" target="_blank" title="查看最大化图片">
                  <img :src="ownerData.licenseImg" style="width: 100%;height: 100%">
                </a>
                <img slot="reference" :src="ownerData.licenseImg" class="carImg" style="cursor:pointer">
              </el-popover>
              <el-upload
                class="upload-demo"
                :action="UploadUrl()"
                :headers="header"
                :show-file-list="false"
                :on-success="handleIntoImgSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>
          </el-collapse-item>
        </el-collapse>

      </div>

      <div>
        <aside>订单信息</aside>
      </div>
      <el-table :data="gridData">
        <el-table-column property="orderNo" label="订单编号" width="150" />
        <el-table-column property="createTime" label="订单时间" width="200">
          <template slot-scope="{row}">
            <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column property="userIdNo" label="客户账号" />
        <el-table-column property="orderAmount" label="订单金额" />
        <el-table-column property="payType" label="支付方式" />
        <el-table-column label="状态">
          <template slot-scope="{row}">
            <span>{{ row.state | orderState(row.state) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <el-button size="mini" @click="orderDetial(row.id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="gridListTotal.totalRow>0"
        :total="gridListTotal.totalRow"
        :page.sync="gridListTotal.pageNum"
        :limt.sync="gridListTotal.pageSize"
        @pagination="getList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">关闭</el-button>
        <el-button type="primary" @click="updateData()">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看详情" :visible.sync="dialogFormVisible1">
      <el-form ref="dataForm" :model="temp" label-position="right" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item label="订单预计装货时间">
          <el-date-picker
            v-model="temp.shipmentTime.start"
            readonly
            :picker-options="pickerOptions0"
            placeholder="选择日期"
            type="datetime"
            value-format="timestamp"
            format="yyyy-MM-dd HH 时"
          />
          <!-- <el-time-select
            v-model="shipmentTime.time"
            align="center"
            :picker-options="{
              start: '00:00',
              step: '01:00',
              end: '24:00'
            }"
            placeholder="选择时间"
            @change="changeTime"
          /> -->
          <!-- <el-date-picker v-model="temp.shipmentTime.start" type="datetime" placeholder="Please pick a date" /> -->
        </el-form-item>
        <!-- <el-form-item label="订单接单最晚时间" prop="timestamp">
          <el-date-picker v-model="temp.shipmentTime.end" type="datetime" placeholder="Please pick a date" />
        </el-form-item> -->
        <el-form-item label="订单预计送达时间">

          <el-date-picker
            v-model="temp.arrivalTime.start"
            readonly
            :picker-options="pickerOptions0"
            placeholder="选择日期"
            type="datetime"
            value-format="timestamp"
            format="yyyy-MM-dd HH 时"
          />
          <!-- <el-date-picker v-model="temp.arrivalTime.start" type="datetime" placeholder="Please pick a date" /> -->
        </el-form-item>
        <!-- <el-form-item label="订单预计送达最晚时间" prop="timestamp">
          <el-date-picker v-model="temp.arrivalTime.end" type="datetime" placeholder="Please pick a date" />
        </el-form-item> -->

        <el-form-item label="货物名称">
          <el-input v-model="temp.freightName" placeholder="请输入货物名称" readonly />
        </el-form-item>
        <el-form-item label="货物最小重量">
          <el-input v-model="temp.freightWeight.min" placeholder="货物最小重量" readonly />吨
        </el-form-item>
        <el-form-item label="货物最大重量">
          <el-input v-model="temp.freightWeight.max" placeholder="货物最大重量" readonly />吨
        </el-form-item>

        <el-form-item label="货物最小体积">
          <el-input v-model="temp.freightBulk.min" placeholder="货物最小体积" readonly />方
        </el-form-item>
        <el-form-item label="货物最大体积">
          <el-input v-model="temp.freightBulk.max" placeholder="货物最大体积" readonly />方
        </el-form-item>
        <el-form-item label="出发地地址">
          <el-input v-model="temp.from.city" placeholder="详细地址" readonly />
          <el-input v-model="temp.from.address" placeholder="详细地址" readonly />
        </el-form-item>
        <el-form-item label="收货地地址">
          <el-input v-model="temp.to.city" placeholder="详细地址" readonly />
          <el-input v-model="temp.to.address" placeholder="详细地址" readonly />
        </el-form-item>

        <el-form-item label="用车类型">
          <el-input v-model="temp.useVehicleType" placeholder="请输入用车类型" readonly />
        </el-form-item>
        <el-form-item label="车长">
          <el-input v-model="temp.vehicleLen" placeholder="请输入车长" readonly />
        </el-form-item>
        <el-form-item label="车型">
          <el-input v-model="temp.vehicleModel" placeholder="请输入车型" readonly />
        </el-form-item>
        <el-form-item label="几装几卸">
          <el-input v-model="temp.hand" placeholder="请输入装卸次数" readonly />
        </el-form-item>

        <el-form-item label="特殊要求">
          <el-input v-model="temp.specialAsk" placeholder="请输入特殊要求" readonly />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remarks" placeholder="请输入备注" readonly />
        </el-form-item>
        <el-form-item label="运费">
          <el-input v-model="temp.freight" placeholder="Please input" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="Type" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="Date" prop="timestamp">
          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="Please pick a date" />
        </el-form-item>
        <el-form-item label="Title" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="Status">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="Imp">
          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />
        </el-form-item>
        <el-form-item label="Remark">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle, getTotal, searchList, stopCar, backCar, getOwnerDetail, getOwnerOrderList, addPic } from '@/api/owner'
import { getDetail } from '@/api/order'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import '../../styles/car.scss'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const orderStateDate = []
orderStateDate[-1] = '货主取消订单'
orderStateDate[-2] = '货主申请取消订单'
orderStateDate[-4] = '司机取消订单'
orderStateDate[0] = '待接货'
orderStateDate[1] = '已接单'
orderStateDate[2] = '已装货'
orderStateDate[3] = '待发货'
orderStateDate[4] = '待收货'
orderStateDate[5] = '已达到'
orderStateDate[6] = '已完成'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    parseTime: parseTime,

    orderState(type) {
      return orderStateDate[type]
    },

    usertype(type) {
      const usertype = []
      usertype[1] = '司机'
      usertype[2] = '货主'
      return usertype[type]
    }
  },
  data() {
    return {
      header: {
        'consumes': 'multipart/form-data',
        'token': getToken()
      },
      pickerOptions0: {
        disabledDate: (time) => {
          return time.getTime() <= Date.now() - 8.64e7
        }
      },
      dialogTableVisible: false,
      dialogFormVisible1: false,
      tableKey: 0,
      list: null,
      carTotal: {
        vehicleTotal: 0,
        ownerOnline: 0,
        ownerDisOnline: 0,
        stopTotal: 0
      },
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        importance: undefined,
        title: undefined,
        state: undefined,
        orderId: undefined,
        driverName: undefined

        // sort: '+id'
      },
      search: {
        number: '',
        pageNum: 1,
        pageSize: 20
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      // temp: {
      //   id: undefined,
      //   importance: 1,
      //   remark: '',
      //   timestamp: new Date(),
      //   title: '',
      //   type: '',
      //   status: 'published'
      // },

      temp: {
        arrivalTime: {
          end: new Date(),
          start: new Date()
        },
        freight: 0,
        freightBulk: {
          max: 1,
          min: 1
        },
        freightName: '',
        freightWeight: {
          max: 1,
          min: 1
        },
        from: {
          address: '',
          city: [],
          province: ''
        },
        hand: '',
        remarks: '',
        shipmentTime: {
          end: new Date(),
          start: new Date()
        },
        specialAsk: [],
        to: {
          address: '',
          city: [],
          province: ''
        },
        useVehicleType: '',
        vehicleLen: '',
        vehicleModel: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,

      gridData: [],
      gridListTotal: {
        pageNum: 1,
        pageSize: 20,
        totalRow: 0
      },
      ownerData: {
        companyState: '',
        idState: '',
        licenseImg: '',
        selfImg: '',
        reverseImg: ''
      },
      editOwner: {
        headImg: ''
      },

      ownerTotalData: [
        {
          outcome: 0,
          orderTotal: 0,
          commentTotal: 0
        }
      ]
    }
  },
  created() {
    this.getTotal()
    this.getList()
  },
  methods: {

    UploadUrl() {
      // var url="/web/file/img/upload/"
      var url = 'https://www.gdhtc.cn//web/file/img/upload/'
      return url
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        console.log(response.result)
        this.list = response.result
        this.total = response.page.totalRow

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getTotal() {
      this.listLoading = true
      getTotal().then(response => {
        this.carTotal = response.result
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter(typeDate) {
      if (!isNaN(typeDate)) {
        console.log('sss' + typeDate)
        this.listQuery.state = typeDate
      } else {
        console.log(typeDate)
        this.listQuery.state = ''
      }
      const arr = this.listQuery
      for (const key in arr) {
        // 去除对象内多余的空值key
        if (arr[key] === '') {
          delete arr[key]
        }
      }
      this.listQuery = arr
      this.listQuery.pageNum = 1
      this.getList()
    },
    // 搜索更新列表
    searchList() {
      this.listLoading = true
      searchList(this.search).then(response => {
        console.log(response.result)
        this.list = response.result
        this.total = response.page.totalRow

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    stopCar(id) {
      this.listLoading = true

      stopCar(id).then(response => {
        console.log(response.result)
        this.getTotal()
        this.getList()

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    backCar(id) {
      this.listLoading = true
      backCar(id).then(response => {
        console.log(response.result)
        this.getTotal()
        this.getList()

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      updateArticle(this.editOwner).then(response => {
        this.$notify({
          title: '编辑成功',
          message: '编辑成功',
          type: 'success',
          duration: 2000
        })
        this.dialogTableVisible = false
        this.getTotal()
        this.getList()
      })
    },
    handleDelete(row) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'orderNo', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'orderNo', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    },
    openDetail(id) {
      console.log(id)
      // var dialogTableVisible = !this.dialogTableVisible
      this.userId = id
      this.dialogTableVisible = !this.dialogTableVisible
      getOwnerDetail(id).then(response => {
        this.ownerData = response.result
        console.log(this.ownerData)
        this.editOwner = response.result
        this.ownerTotalData[0].outcome = response.result.outcome
        this.ownerTotalData[0].orderTotal = response.result.orderTotal
        this.ownerTotalData[0].commentTotal = response.result.commentTotal
        this.getOwnerOrderList(id)
        console.log(this.ownerTotalData)
        console.log(response)
      })
    },
    handleAvatarSuccess(res, file) {
      // this.editOwner.headImg1 = res.result.id
      console.log(this.editOwner)
      this.ownerData.headImg = res.result.fileUrl
      this.editOwner.headImg = res.result.fileUrl
      // this.imageUrl = createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    getOwnerOrderList(id) {
      getOwnerOrderList(id).then(response2 => {
        console.log(response2)
        this.gridData = response2.result
        this.gridListTotal = response2.page
      })
      console.log(this.gridListTotal)
    },
    handleIdCardImgBSuccess(res, file) {
    // this.editOwner.pictures.idCardImgB1 = res.result.id
      console.log(this.editOwner)
      if (!this.ownerData.frontImg) {
        var param = {
          state: 1,
          userId: this.userId,
          frontImg: res.result.id
        }
        addPic(param).then(res => {
          console.log(res)
        })
      }
      this.ownerData.frontImg = res.result.fileUrl
      this.editOwner.frontImg = res.result.fileUrl
    // this.imageUrl = createObjectURL(file.raw)
    },

    handleIdCardImgFSuccess(res, file) {
      // this.editOwner.pictures.idCardImgF1 = res.result.id
      console.log(this.editOwner)
      if (!this.ownerData.reverseImg) {
        var param = {
          state: 1,
          userId: this.userId,
          reverseImg: res.result.id
        }
        addPic(param).then(res => {
          console.log(res)
        })
      }
      this.ownerData.reverseImg = res.result.fileUrl
      this.editOwner.reverseImg = res.result.fileUrl
      // this.imageUrl = createObjectURL(file.raw)
    },

    handleSelfImgSuccess(res, file) {
      // this.editOwner.pictures.idCardImgF1 = res.result.id
      console.log(this.editOwner)
      if (!this.ownerData.selfImg) {
        var param = {
          state: 1,
          userId: this.userId,
          selfImg: res.result.id
        }
        addPic(param).then(res => {
          console.log(res)
        })
      }
      this.ownerData.selfImg = res.result.fileUrl
      this.editOwner.selfImg = res.result.fileUrl
      // this.imageUrl = createObjectURL(file.raw)
    },
    handleIntoImgSuccess(res, file) {
      console.log(this.editOwner)
      if (!this.ownerData.licenseImg) {
        var param = {
          state: 1,
          userId: this.userId,
          attachInfo: {
            licenseImg: res.result.id,
            companyName: ''
          }
        }
        addPic(param).then(res => {
          console.log(res)
        })
      }
      this.ownerData.licenseImg = res.result.fileUrl
      this.editOwner.licenseImg = res.result.fileUrl
    },
    orderDetial(id) {
      this.dialogFormVisible1 = !this.dialogFormVisible1
      getDetail(id).then(response => {
        this.temp = response.result
        this.temp.shipmentTime.start = this.temp.shipmentTime.start * 1000
        this.temp.arrivalTime.start = this.temp.arrivalTime.start * 1000
        this.temp.specialAsk = this.temp.specialAsk.toString()
        console.log(this.temp)
        this.dialogFormVisible1 = true
      })
    }
  }
}
</script>
<style>
.tableTitle {
  width: 150px;
  padding-right: 20px;
  text-align: right;
  font-weight: bold;
}

.authTable tr{
  height: 50px;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    display: block;
  }
</style>
